"use strict";
cc._RF.push(module, '4c056elkyRLIY9kNm2YzIMe', 'level_cardComposition');
// scripts/levelBundles/level_cardComposition/level_cardComposition.ts

"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var LevelBase_1 = require("../../Game/Base/LevelBase");
var Enum_1 = require("../../Game/Enum");
var MainRoot_1 = require("../../Game/MainRoot");
var gameEngine_1 = require("../../engines/gameEngine");
var CsvFileKind_1 = require("../../engines/libs/CsvFileKind");
var data_control_1 = require("../../engines/libs/data_control");
var level_cardComposition_card_1 = require("./base/level_cardComposition_card");
var level_cardComposition_cardGroup_1 = require("./base/level_cardComposition_cardGroup");
var level_cardCompositionConst_1 = require("./const/level_cardCompositionConst");
var _a = cc._decorator, ccclass = _a.ccclass, property = _a.property;
var level_cardComposition = /** @class */ (function (_super) {
    __extends(level_cardComposition, _super);
    function level_cardComposition() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.groupContent = null;
        _this.cardContent = null;
        _this.cardP = null;
        _this.groupP = null;
        _this.touchNode = null;
        _this.coloured = null;
        _this.inGamePage = null;
        _this.cardStrAry = [
            "A",
            "2",
            "3",
            "4",
            "5",
            "6",
            "7",
            "8",
            "9",
            "10",
            "J",
            "Q",
            "K",
        ];
        /**卡牌节点池 */
        _this.cardPool = new cc.NodePool();
        /**游戏阶段数组 */
        _this.phaseTargetAry = [];
        /**需要解锁的所有组 */
        _this.needUnlockGroupAry = [];
        /**当前游戏阶段 */
        _this.curStep = -1;
        /**最大的卡牌 */
        _this.maxCardNum = 0;
        /**创建的最小的卡牌 */
        _this.createMinCardNum = 0;
        _this.startCreateMaxCard = 0;
        /**当前点击的节点 */
        _this.curSelectNode = null;
        /**是否可以点击 */
        _this.canTouch = true;
        _this.levelData = null;
        _this.compositionCards = [
            [2, 6, 10],
            [1, 5, 9],
            [3, 7, 11],
            [0, 4, 8, 12]
        ];
        _this.colorArys = [
            [],
            [],
            [],
            []
        ];
        _this.colorArysCopy = [
            [cc.color(230, 0, 18), cc.color(255, 97, 0)],
            [cc.color(0, 153, 68), cc.color(0, 158, 150)],
            [cc.color(0, 160, 233), cc.color(29, 32, 136)],
            [cc.color(146, 7, 131), cc.color(229, 0, 79)],
        ];
        _this.groupPos = [
            cc.v2(-280, 5),
            cc.v2(-140, 5),
            cc.v2(-0, 5),
            cc.v2(140, 5),
            cc.v2(280, 5),
            cc.v2(-280, 495),
            cc.v2(-140, 495),
            cc.v2(-0, 495),
            cc.v2(140, 495),
            cc.v2(280, 495),
        ];
        _this.colorMap = {};
        _this.dealFlag = false;
        _this.introductionStack = [];
        /**缓存的key */
        _this.save_data_key = "user-data-card-composition-save-key";
        _this._introductionAry = [];
        _this.openIntroductionFlag = false;
        return _this;
    }
    /**加载数据 */
    level_cardComposition.prototype.loadData = function () {
        var dataStr = gameEngine_1.default.getServices().localStorageSrv.getStorage(this.save_data_key) || "[]";
        var data = JSON.parse(dataStr);
        this._introductionAry = data;
    };
    level_cardComposition.prototype.writeData = function () {
        gameEngine_1.default.getServices().localStorageSrv.setStorage(this.save_data_key, JSON.stringify(this._introductionAry));
    };
    level_cardComposition.prototype.Init = function (info) {
        return __awaiter(this, void 0, Promise, function () {
            var inGamePrams, minCard, maxCard, phaseStr, cLength, _loop_1, this_1, i, _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        this.loadData();
                        this.levelInfo = info;
                        this.m_mode = info.mode;
                        this.tips = info.tips;
                        inGamePrams = {
                            mode: this.m_mode,
                            levelInfo: this.levelInfo,
                            title: info.title,
                            tips: info.tips,
                            hideTitle: info.hideTitle
                        };
                        gameEngine_1.default.on(Enum_1.GAME_EVENT.ON_BTN_TIPS, this.OnTips.bind(this));
                        this.levelData = gameEngine_1.default.getManagers().csvDataManager.getCsvDataItem(CsvFileKind_1.CsvFileKind.CsvFile.cardCompositionLevel, this.levelInfo.level);
                        minCard = Number(this.levelData["min_card"]);
                        maxCard = Number(this.levelData["max_card"]);
                        this.createMinCardNum = minCard;
                        this.startCreateMaxCard = maxCard;
                        gameEngine_1.default.getManagers().soundMgr.loadSoundBundle("cardComposition");
                        phaseStr = this.levelData["phase_target"];
                        this.phaseTargetAry = phaseStr.split("|").map(function (v) {
                            return Number(v);
                        });
                        cLength = level_cardCompositionConst_1.level_cardCompositionE.LENGTH - 1;
                        _loop_1 = function (i) {
                            var aryIndex = this_1.compositionCards.findIndex(function (v) {
                                return v.includes(i);
                            });
                            if (this_1.colorArys[aryIndex].length <= 0) {
                                this_1.colorArys[aryIndex] = data_control_1.default.randomSortArray(this_1.colorArysCopy[aryIndex].concat());
                            }
                            this_1.colorMap[i] = this_1.colorArys[aryIndex].pop();
                        };
                        this_1 = this;
                        for (i = 0; i < cLength; i++) {
                            _loop_1(i);
                        }
                        this.initGroup();
                        _a = this;
                        return [4 /*yield*/, MainRoot_1.default.UISystem.OpenPage(Enum_1.PAGE.CARD_COMPOSITION_INGAME_PAGE, inGamePrams)];
                    case 1:
                        _a.inGamePage = (_b.sent());
                        this.inGamePage.bindLevel(this);
                        this.createCards(true, false, false);
                        this.touchNodeAddEvent();
                        this.canTouch = true;
                        this.dealFlag = true;
                        return [2 /*return*/];
                }
            });
        });
    };
    level_cardComposition.prototype.onLoad = function () {
    };
    level_cardComposition.prototype.start = function () {
    };
    /**初始化组 */
    level_cardComposition.prototype.initGroup = function () {
        var _this = this;
        var defaultGroup = Number(this.levelData["default_group"]);
        for (var i = 0; i < this.groupPos.length; i++) {
            var group = cc.instantiate(this.groupP);
            group.setParent(this.groupContent);
            group.setPosition(this.groupPos[i]);
            var gs = group.getComponent(level_cardComposition_cardGroup_1.default);
            if (i < defaultGroup) {
                gs.setGroupType(level_cardCompositionConst_1.level_cardCompositionGroupTypeE.normal);
            }
            else if (i < defaultGroup + this.phaseTargetAry.length - 1) {
                gs.setGroupType(level_cardCompositionConst_1.level_cardCompositionGroupTypeE.unlock);
            }
            else {
                gs.setGroupType(level_cardCompositionConst_1.level_cardCompositionGroupTypeE.temp);
            }
        }
        this.groupContent.children.forEach(function (group) {
            var gs = group.getComponent(level_cardComposition_cardGroup_1.default);
            gs.bindData(_this);
            if (gs.groupType == level_cardCompositionConst_1.level_cardCompositionGroupTypeE.unlock) {
                gs.setTargetLb("\u5408\u6210" + _this.cardStrAry[_this.phaseTargetAry[_this.needUnlockGroupAry.length]] + "\n\u89E3\u9501");
                _this.needUnlockGroupAry.push(gs);
            }
        });
    };
    level_cardComposition.prototype.touchNodeAddEvent = function () {
        this.touchNode.on('touchend', this.onTouchEndTouchNode, this);
    };
    level_cardComposition.prototype.onTouchEndTouchNode = function (e) {
        return __awaiter(this, void 0, void 0, function () {
            var targetNode, cs, cs, cs_1, ts_1, cMoveCards, pushCardFlag, cardOver, moveCards, _loop_2, i, state_1, _i, moveCards_1, c;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.canTouch) {
                            return [2 /*return*/];
                        }
                        this.canTouch = false;
                        targetNode = null;
                        this.groupContent.children.forEach(function (n) {
                            var nBound = n.getBoundingBoxToWorld();
                            if (nBound.contains(e.getLocation())) {
                                targetNode = n;
                            }
                        });
                        if (!targetNode) {
                            if (this.curSelectNode) {
                                cs = this.curSelectNode.getComponent(level_cardComposition_cardGroup_1.default);
                                cs.setMoveCardSelect(false);
                            }
                            this.curSelectNode = null;
                            this.canTouch = true;
                            return [2 /*return*/];
                        }
                        if (!!this.curSelectNode) return [3 /*break*/, 1];
                        this.curSelectNode = targetNode;
                        cs = this.curSelectNode.getComponent(level_cardComposition_cardGroup_1.default);
                        cs.setMoveCardSelect(true);
                        return [3 /*break*/, 6];
                    case 1:
                        cs_1 = this.curSelectNode.getComponent(level_cardComposition_cardGroup_1.default);
                        ts_1 = targetNode.getComponent(level_cardComposition_cardGroup_1.default);
                        if (targetNode.uuid == this.curSelectNode.uuid) {
                            cs_1.setMoveCardSelect(false);
                            this.curSelectNode = null;
                            this.canTouch = true;
                            return [2 /*return*/];
                        }
                        cMoveCards = cs_1.getMoveCards();
                        pushCardFlag = false;
                        cardOver = false;
                        moveCards = [];
                        _loop_2 = function (i) {
                            var card;
                            return __generator(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        card = cMoveCards[i];
                                        if (!ts_1.checkCanPushCard(card)) return [3 /*break*/, 2];
                                        if (i == cMoveCards.length - 1) {
                                            cardOver = true;
                                        }
                                        pushCardFlag = true;
                                        moveCards.push(card);
                                        return [4 /*yield*/, new Promise(function (resolve) {
                                                card.setSelect(false);
                                                cs_1.spliceCard(card);
                                                ts_1.pushCard(card);
                                                _this.scheduleOnce(resolve, 0.05);
                                            })];
                                    case 1:
                                        _a.sent();
                                        return [3 /*break*/, 3];
                                    case 2: return [2 /*return*/, "break"];
                                    case 3: return [2 /*return*/];
                                }
                            });
                        };
                        i = 0;
                        _a.label = 2;
                    case 2:
                        if (!(i < cMoveCards.length)) return [3 /*break*/, 5];
                        return [5 /*yield**/, _loop_2(i)];
                    case 3:
                        state_1 = _a.sent();
                        if (state_1 === "break")
                            return [3 /*break*/, 5];
                        _a.label = 4;
                    case 4:
                        i++;
                        return [3 /*break*/, 2];
                    case 5:
                        // ts.pushCardEnd();
                        for (_i = 0, moveCards_1 = moveCards; _i < moveCards_1.length; _i++) {
                            c = moveCards_1[_i];
                            c.onSpliceToGroup();
                            c.onPushToGroup();
                        }
                        // cs.spliceCardEnd();
                        cs_1.changeState();
                        if (!pushCardFlag) {
                            // 没有移动卡牌 切换选择的卡牌
                            cs_1.setMoveCardSelect(false);
                            ts_1.setMoveCardSelect(true);
                            this.curSelectNode = targetNode;
                        }
                        else {
                            // if(!cs.getLastCard() || cardOver){
                            cs_1.setMoveCardSelect(false);
                            this.curSelectNode = null;
                            // }
                        }
                        _a.label = 6;
                    case 6:
                        this.canTouch = true;
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     * 创建指定点数的卡牌
     * @param cardComposition 点数
     * @param length 数量
     */
    level_cardComposition.prototype.createAssignTypeCard = function (cardComposition, length, targetGroup) {
        return __awaiter(this, void 0, void 0, function () {
            var cards, cardNode;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.createCardForCount(length, cardComposition, level_cardCompositionConst_1.level_cardCompositionCardType.normal, targetGroup, false, false, false)];
                    case 1:
                        cards = _a.sent();
                        // let cards:level_cardComposition_card[] = [];
                        // for(let i = 0 ; i < length; i++){
                        //     let card = this.getOneCard();
                        //     let cs = card.getComponent(level_cardComposition_card);
                        //     cards.push(cs);
                        //     cs.bindData(cardComposition,level_cardCompositionCardType.normal);
                        //     targetGroup.pushCard(cs,false,false);
                        // }
                        // targetGroup.pushCardEnd(cards);
                        if (cardComposition == this.phaseTargetAry[this.phaseTargetAry.length - 1]) {
                            cardNode = cards[cards.length - 1].node;
                            cardNode.zIndex = cc.macro.MAX_ZINDEX;
                            //@ts-ignore
                            cc.tween(cardNode).to(1, { position: cc.v2(0, 0) }).call(function () {
                                _this.coloured.active = true;
                                _this.Win(3);
                            }).start();
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    level_cardComposition.prototype.createCards = function (isStart, hasAni, soundFlag) {
        if (isStart === void 0) { isStart = false; }
        if (hasAni === void 0) { hasAni = true; }
        if (soundFlag === void 0) { soundFlag = true; }
        return __awaiter(this, void 0, void 0, function () {
            var canDealGroups, fillCountAry, dealCountAry, dealCount, fillCount, createCountAry, maxCreateIndex, secondCreateIndex, maxCreate, secondCreate, i, maxCreateCount, minCreateNum, createCount, maxCutProAry, maxThreeCutProAry, secondCutProAry, step, maxCutPro, maxThreeCutPro, secondCutPro, maxScore, maxCardScore, minCardScore, numAry, i, createCardScoreAry, getOneCreateScore, firstCutCountAry, seconCutCountAry, firstWeight, secondWeight, firstCutType, secondCutType, firstCutCount, secondCutCount, allCutCount, secondMaxIndexAry, createCutCount, common_pro, obstaclesPro, query_pro, createTypeWeightAryByQuery, createTypeWeightAry, i, createCount, group, createCounts, queryFlag, type, j, j, curjCreateCount, score, type, _a, createCounts, queryFlag, type, j, j, curjCreateCount, score, type, _b, type, score, _c;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        canDealGroups = this.getCanDealCardGroup();
                        canDealGroups = data_control_1.default.randomSortArray(canDealGroups);
                        fillCountAry = this.levelData["fill_num"].split("|").map(function (v) {
                            return Number(v);
                        });
                        dealCountAry = this.levelData["deal_num"].split("|").map(function (v) {
                            return Number(v);
                        });
                        dealCount = dealCountAry[canDealGroups.length - 1];
                        fillCount = fillCountAry[canDealGroups.length - 1];
                        if (isStart) {
                            fillCount = 0;
                        }
                        createCountAry = [];
                        maxCreateIndex = -1;
                        secondCreateIndex = -1;
                        maxCreate = 0;
                        secondCreate = 0;
                        for (i = 0; i < dealCount; i++) {
                            maxCreateCount = Math.ceil((canDealGroups[i].getMaxCardsLength() - canDealGroups[i].getCurCardsLength()) / 2);
                            maxCreateCount = Math.max(maxCreateCount, 1);
                            minCreateNum = 1;
                            createCount = Math.ceil(data_control_1.default.getRandNumberOfArrayTwo([minCreateNum, maxCreateCount]));
                            if (i < fillCount) {
                                createCount = canDealGroups[i].getMaxCardsLength() - canDealGroups[i].getCurCardsLength();
                            }
                            if (createCount > maxCreate) {
                                maxCreate = createCount;
                                maxCreateIndex = i;
                            }
                            if (createCount > secondCreate && createCount <= maxCreate && i != maxCreateIndex) {
                                secondCreate = createCount;
                                secondCreateIndex = i;
                            }
                            createCountAry.push(createCount);
                        }
                        maxCutProAry = this.levelData["first_two_pro"].split("|").map(function (v) {
                            return Number(v);
                        });
                        maxThreeCutProAry = this.levelData["first_three_pro"].split("|").map(function (v) {
                            return Number(v);
                        });
                        secondCutProAry = this.levelData["second_cut_pro"].split("|").map(function (v) {
                            return Number(v);
                        });
                        step = Math.max(this.curStep, 0);
                        maxCutPro = maxCutProAry[step];
                        maxThreeCutPro = maxThreeCutProAry[step];
                        secondCutPro = secondCutProAry[step];
                        maxScore = Math.max(this.startCreateMaxCard, this.maxCardNum);
                        maxCardScore = Math.max(maxScore - 1, this.createMinCardNum);
                        minCardScore = this.createMinCardNum;
                        numAry = [];
                        for (i = minCardScore; i <= maxCardScore; i++) {
                            numAry.push(i);
                        }
                        createCardScoreAry = [];
                        getOneCreateScore = function () {
                            if (createCardScoreAry.length <= 0) {
                                createCardScoreAry = data_control_1.default.randomSortArray(numAry.concat());
                            }
                            return createCardScoreAry.pop();
                        };
                        firstCutCountAry = [1, 2, 3];
                        seconCutCountAry = [1, 2];
                        firstWeight = [1 - maxCutPro - maxThreeCutPro, maxCutPro, maxThreeCutPro];
                        secondWeight = [1 - secondCutPro, secondCutPro];
                        firstCutType = data_control_1.default.getRandIPosByWeights(firstWeight);
                        secondCutType = data_control_1.default.getRandIPosByWeights(secondWeight);
                        firstCutCount = createCountAry[maxCreateIndex] >= firstCutCountAry[firstCutType] ? firstCutCountAry[firstCutType] : createCountAry[maxCreateIndex];
                        secondCutCount = createCountAry[secondCreateIndex] >= seconCutCountAry[secondCutType] ? seconCutCountAry[secondCutType] : createCountAry[secondCreateIndex];
                        allCutCount = dealCount + firstCutType + secondCutType;
                        secondMaxIndexAry = [];
                        createCutCount = 0;
                        common_pro = Number(this.levelData["common_pro"]);
                        obstaclesPro = Number(this.levelData["obstacle_pro"]);
                        query_pro = Number(this.levelData["query_pro"]);
                        createTypeWeightAryByQuery = [1 - common_pro - obstaclesPro - query_pro, common_pro, obstaclesPro, query_pro];
                        createTypeWeightAry = [1 - common_pro - obstaclesPro, common_pro, obstaclesPro];
                        i = 0;
                        _d.label = 1;
                    case 1:
                        if (!(i < dealCount)) return [3 /*break*/, 36];
                        createCount = createCountAry[i];
                        group = canDealGroups[i];
                        if (!(i == maxCreateIndex)) return [3 /*break*/, 14];
                        createCounts = new Array(firstCutCount).fill(0);
                        queryFlag = false;
                        if (createCounts.length > 1) {
                            type = data_control_1.default.getRandIPosByWeights(createTypeWeightAryByQuery);
                            if (type == 3) {
                                queryFlag = true;
                            }
                        }
                        for (j = 0; j < createCount; j++) {
                            createCounts[j % firstCutCount]++;
                        }
                        j = 0;
                        _d.label = 2;
                    case 2:
                        if (!(j < createCounts.length)) return [3 /*break*/, 13];
                        curjCreateCount = createCounts[j];
                        score = null;
                        if (!(j == 0 && queryFlag)) return [3 /*break*/, 4];
                        if (secondMaxIndexAry.includes(createCutCount)) {
                            score = maxCardScore;
                        }
                        else {
                            score = getOneCreateScore();
                        }
                        return [4 /*yield*/, this.createCardForCount(curjCreateCount, score, level_cardCompositionConst_1.level_cardCompositionCardType.query, group, false, hasAni, soundFlag)];
                    case 3:
                        _d.sent();
                        return [3 /*break*/, 11];
                    case 4:
                        type = data_control_1.default.getRandIPosByWeights(createTypeWeightAry);
                        _a = type;
                        switch (_a) {
                            case 0: return [3 /*break*/, 5];
                            case 1: return [3 /*break*/, 7];
                            case 2: return [3 /*break*/, 9];
                        }
                        return [3 /*break*/, 11];
                    case 5:
                        if (secondMaxIndexAry.includes(createCutCount)) {
                            score = maxCardScore;
                        }
                        else {
                            score = getOneCreateScore();
                        }
                        return [4 /*yield*/, this.createCardForCount(curjCreateCount, score, level_cardCompositionConst_1.level_cardCompositionCardType.normal, group, false, hasAni, soundFlag)];
                    case 6:
                        _d.sent();
                        return [3 /*break*/, 11];
                    case 7: return [4 /*yield*/, this.createCardForCount(curjCreateCount, null, level_cardCompositionConst_1.level_cardCompositionCardType.universal, group, false, hasAni, soundFlag)];
                    case 8:
                        _d.sent();
                        return [3 /*break*/, 11];
                    case 9: return [4 /*yield*/, this.createCardForCount(curjCreateCount, null, level_cardCompositionConst_1.level_cardCompositionCardType.obstacles, group, false, hasAni, soundFlag)];
                    case 10:
                        _d.sent();
                        return [3 /*break*/, 11];
                    case 11:
                        createCutCount++;
                        _d.label = 12;
                    case 12:
                        j++;
                        return [3 /*break*/, 2];
                    case 13: return [3 /*break*/, 35];
                    case 14:
                        if (!(i == secondCreateIndex)) return [3 /*break*/, 27];
                        createCounts = new Array(secondCutCount).fill(0);
                        queryFlag = false;
                        if (createCounts.length > 1) {
                            type = data_control_1.default.getRandIPosByWeights(createTypeWeightAryByQuery);
                            if (type == 3) {
                                queryFlag = true;
                            }
                        }
                        for (j = 0; j < createCount; j++) {
                            createCounts[j % secondCutCount]++;
                        }
                        j = 0;
                        _d.label = 15;
                    case 15:
                        if (!(j < createCounts.length)) return [3 /*break*/, 26];
                        curjCreateCount = createCounts[j];
                        score = null;
                        if (!(j == 0 && queryFlag)) return [3 /*break*/, 17];
                        if (secondMaxIndexAry.includes(createCutCount)) {
                            score = maxCardScore;
                        }
                        else {
                            score = getOneCreateScore();
                        }
                        return [4 /*yield*/, this.createCardForCount(curjCreateCount, score, level_cardCompositionConst_1.level_cardCompositionCardType.query, group, false, hasAni, soundFlag)];
                    case 16:
                        _d.sent();
                        return [3 /*break*/, 24];
                    case 17:
                        type = data_control_1.default.getRandIPosByWeights(createTypeWeightAry);
                        _b = type;
                        switch (_b) {
                            case 0: return [3 /*break*/, 18];
                            case 1: return [3 /*break*/, 20];
                            case 2: return [3 /*break*/, 22];
                        }
                        return [3 /*break*/, 24];
                    case 18:
                        if (secondMaxIndexAry.includes(createCutCount)) {
                            score = maxCardScore;
                        }
                        else {
                            score = getOneCreateScore();
                        }
                        return [4 /*yield*/, this.createCardForCount(curjCreateCount, score, level_cardCompositionConst_1.level_cardCompositionCardType.normal, group, false, hasAni, soundFlag)];
                    case 19:
                        _d.sent();
                        return [3 /*break*/, 24];
                    case 20: return [4 /*yield*/, this.createCardForCount(curjCreateCount, null, level_cardCompositionConst_1.level_cardCompositionCardType.universal, group, false, hasAni, soundFlag)];
                    case 21:
                        _d.sent();
                        return [3 /*break*/, 24];
                    case 22: return [4 /*yield*/, this.createCardForCount(curjCreateCount, null, level_cardCompositionConst_1.level_cardCompositionCardType.obstacles, group, false, hasAni, soundFlag)];
                    case 23:
                        _d.sent();
                        return [3 /*break*/, 24];
                    case 24:
                        createCutCount++;
                        _d.label = 25;
                    case 25:
                        j++;
                        return [3 /*break*/, 15];
                    case 26: return [3 /*break*/, 35];
                    case 27:
                        type = data_control_1.default.getRandIPosByWeights(createTypeWeightAry);
                        score = null;
                        _c = type;
                        switch (_c) {
                            case 0: return [3 /*break*/, 28];
                            case 1: return [3 /*break*/, 30];
                            case 2: return [3 /*break*/, 32];
                        }
                        return [3 /*break*/, 34];
                    case 28:
                        if (secondMaxIndexAry.includes(createCutCount)) {
                            score = maxCardScore;
                        }
                        else {
                            score = getOneCreateScore();
                        }
                        return [4 /*yield*/, this.createCardForCount(createCount, score, level_cardCompositionConst_1.level_cardCompositionCardType.normal, group, false, hasAni, soundFlag)];
                    case 29:
                        _d.sent();
                        return [3 /*break*/, 34];
                    case 30: return [4 /*yield*/, this.createCardForCount(createCount, null, level_cardCompositionConst_1.level_cardCompositionCardType.universal, group, false, hasAni, soundFlag)];
                    case 31:
                        _d.sent();
                        return [3 /*break*/, 34];
                    case 32: return [4 /*yield*/, this.createCardForCount(createCount, null, level_cardCompositionConst_1.level_cardCompositionCardType.obstacles, group, false, hasAni, soundFlag)];
                    case 33:
                        _d.sent();
                        return [3 /*break*/, 34];
                    case 34:
                        createCutCount++;
                        _d.label = 35;
                    case 35:
                        i++;
                        return [3 /*break*/, 1];
                    case 36:
                        this.checkCanWashCard();
                        return [2 /*return*/];
                }
            });
        });
    };
    /** 创建卡牌 */
    level_cardComposition.prototype.createCardForCount = function (createNum, cardScore, cardType, group, isJudge, hasAni, soundFlag) {
        if (hasAni === void 0) { hasAni = true; }
        if (soundFlag === void 0) { soundFlag = true; }
        return __awaiter(this, void 0, void 0, function () {
            var _this = this;
            return __generator(this, function (_a) {
                switch (cardType) {
                    case level_cardCompositionConst_1.level_cardCompositionCardType.query: {
                        this.introductionStack.push("1");
                        break;
                    }
                    case level_cardCompositionConst_1.level_cardCompositionCardType.universal: {
                        this.introductionStack.push("0");
                        break;
                    }
                }
                this.openIntroduction();
                return [2 /*return*/, new Promise(function (resolve) { return __awaiter(_this, void 0, void 0, function () {
                        var cards, k;
                        var _this = this;
                        return __generator(this, function (_a) {
                            switch (_a.label) {
                                case 0:
                                    cards = [];
                                    this.setMaxCard(cardScore);
                                    k = 0;
                                    _a.label = 1;
                                case 1:
                                    if (!(k < createNum)) return [3 /*break*/, 4];
                                    return [4 /*yield*/, new Promise(function (resolve1) {
                                            var card = _this.getOneCard();
                                            card.y = -750;
                                            var cs = card.getComponent(level_cardComposition_card_1.default);
                                            cards.push(cs);
                                            cs.bindData(cardScore, cardType);
                                            group.pushCard(cs, isJudge, hasAni, soundFlag).then(function () {
                                                resolve(cards);
                                            });
                                            // this.scheduleOnce(resolve1);
                                            if (hasAni) {
                                                _this.scheduleOnce(resolve1);
                                            }
                                            else {
                                                resolve1();
                                            }
                                        })];
                                case 2:
                                    _a.sent();
                                    _a.label = 3;
                                case 3:
                                    k++;
                                    return [3 /*break*/, 1];
                                case 4:
                                    group.pushCardEnd(cards);
                                    return [2 /*return*/];
                            }
                        });
                    }); })];
            });
        });
    };
    level_cardComposition.prototype.getCanDealCardGroup = function (leisureNum) {
        if (leisureNum === void 0) { leisureNum = 1; }
        var groupAry = [];
        this.groupContent.children.forEach(function (group) {
            var gs = group.getComponent(level_cardComposition_cardGroup_1.default);
            if (!gs.lockFlag && gs.groupType != level_cardCompositionConst_1.level_cardCompositionGroupTypeE.temp && gs.getMaxCardsLength() - gs.getCurCardsLength() >= leisureNum) {
                groupAry.push(gs);
            }
        });
        return groupAry;
    };
    level_cardComposition.prototype.onBtnSynthesis = function () {
        var _this = this;
        if (!this.canTouch) {
            return;
        }
        this.canTouch = false;
        gameEngine_1.default.getManagers().soundMgr.playSound("cardComposition/click");
        var trueFlag = false;
        this.groupContent.children.forEach(function (group) {
            var _a;
            var gs = group.getComponent(level_cardComposition_cardGroup_1.default);
            var nextType = ((_a = gs === null || gs === void 0 ? void 0 : gs.getLastCard()) === null || _a === void 0 ? void 0 : _a.cardComposition) + 1;
            var soundFlag = false;
            if (gs.checkCanSynthesis()) {
                trueFlag = true;
                var fun = function (isTrue) {
                    if (isTrue) {
                        if (!soundFlag) {
                            soundFlag = true;
                            gameEngine_1.default.getManagers().soundMgr.playSound("cardComposition/HeCheng");
                        }
                        if (_this.curSelectNode && _this.curSelectNode.uuid == group.uuid) {
                            _this.curSelectNode = null;
                        }
                        _this.createAssignTypeCard(nextType, 2, gs).then(function () {
                            if (gs.groupType == level_cardCompositionConst_1.level_cardCompositionGroupTypeE.temp) {
                                gs.checkTempGroupToBack();
                            }
                            _this.canTouch = true;
                            _this.checkCanWashCard();
                        });
                    }
                };
                gs.cardSynthesis().then(fun);
            }
        });
        if (!trueFlag) {
            this.canTouch = true;
        }
    };
    level_cardComposition.prototype.getOneCard = function () {
        if (this.cardPool.size() > 0) {
            var node_1 = this.cardPool.get();
            var ns_1 = node_1.getComponent(level_cardComposition_card_1.default);
            ns_1.initCard(this);
            return node_1;
        }
        var node = cc.instantiate(this.cardP);
        var ns = node.getComponent(level_cardComposition_card_1.default);
        ns.initCard(this);
        return node;
    };
    level_cardComposition.prototype.putOneCard = function (cardNode) {
        this.cardPool.put(cardNode);
    };
    /**
     * 放置一张卡牌的动画
     * @param targetNode 目标节点
     * @param worldPos 世界坐标
     */
    level_cardComposition.prototype.pushCardAni = function (targetNode, worldPos, hasAni, soundFlag) {
        var _this = this;
        if (soundFlag === void 0) { soundFlag = true; }
        return new Promise(function (resolve) {
            targetNode.setParent(_this.cardContent);
            targetNode.zIndex = 1000;
            var needTime = 0.2;
            var targetPos = _this.cardContent.convertToNodeSpaceAR(worldPos);
            if (soundFlag) {
                gameEngine_1.default.getManagers().soundMgr.playSound("cardComposition/YiDong1");
            }
            if (hasAni) {
                //@ts-ignore
                cc.tween(targetNode).to(needTime, { position: targetPos }).call(function () {
                    resolve();
                }).start();
            }
            else {
                targetNode.setPosition(targetPos);
                resolve();
            }
        });
    };
    level_cardComposition.prototype.onBtnDealCard = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        gameEngine_1.default.getManagers().soundMgr.playSound("cardComposition/click");
                        if (!this.canTouch) {
                            return [2 /*return*/];
                        }
                        this.canTouch = false;
                        return [4 /*yield*/, this.createCards(false, true)];
                    case 1:
                        _a.sent();
                        this.canTouch = true;
                        return [2 /*return*/];
                }
            });
        });
    };
    level_cardComposition.prototype.setMaxCard = function (max) {
        if (max > this.maxCardNum) {
            this.maxCardNum = max;
            var phase = -1;
            for (var i = 0; i < this.phaseTargetAry.length; i++) {
                var phaseTarget = this.phaseTargetAry[i];
                if (this.maxCardNum == phaseTarget) {
                    phase = i;
                }
            }
            if (phase > this.curStep) {
                this.curStep = phase;
                this.changeStep();
                // 切换了一个阶段
            }
        }
    };
    /**
     * 更改step
     */
    level_cardComposition.prototype.changeStep = function () {
        var step = this.curStep;
        var unlockGroup = this.needUnlockGroupAry[step];
        unlockGroup === null || unlockGroup === void 0 ? void 0 : unlockGroup.setCanUnlock();
    };
    level_cardComposition.prototype.getRandLeisureGroup = function () {
        var groups = this.getCanDealCardGroup(2);
        if (groups.length > 0) {
            var randGroup = data_control_1.default.getRandItemOfArray(groups);
            return randGroup;
        }
        return null;
    };
    /* 判断是否可以洗牌  */
    level_cardComposition.prototype.checkCanWashCard = function () {
        var dealCount = 0;
        var groups = this.getCanDealCardGroup(0);
        var maxLength = 0;
        groups.forEach(function (gs) {
            var canDealCount = gs.getCurCardsLength();
            dealCount += canDealCount;
            maxLength += gs.getMaxCardsLength();
        });
        var ratio = Number(this.levelData["wash_card_ratio"]) || 0.8;
        // console.log(dealCount,maxLength,dealCount/maxLength,ratio);
        if (dealCount / maxLength >= ratio) {
            this.inGamePage.showWashCard(true);
        }
        else {
            this.inGamePage.showWashCard(false);
        }
    };
    level_cardComposition.prototype.washCard = function () {
        var _this = this;
        var _a;
        if (!this.canTouch) {
            return;
        }
        this.canTouch = false;
        this.inGamePage.showWashCard(false);
        var minCard = level_cardCompositionConst_1.level_cardCompositionE.LENGTH;
        var maxCard = 0;
        gameEngine_1.default.getManagers().soundMgr.playSound("cardComposition/XiPai");
        var cards = [];
        var universalAry = [];
        var obstaclesAry = [];
        this.groupContent.children.forEach(function (group) {
            var gs = group.getComponent(level_cardComposition_cardGroup_1.default);
            var gCards = gs.getCards();
            for (var i = 0; i < gCards.length; i++) {
                var card = gCards[i];
                card.setSelect(false);
                var composition = card.cardComposition;
                if (!cards[composition]) {
                    cards[composition] = [];
                }
                switch (card.cardType) {
                    case level_cardCompositionConst_1.level_cardCompositionCardType.normal: {
                        cards[composition].push(card);
                        minCard = Math.min(composition, minCard);
                        maxCard = Math.max(composition, maxCard);
                        break;
                    }
                    case level_cardCompositionConst_1.level_cardCompositionCardType.universal: {
                        universalAry.push(card);
                        card.onSpliceToGroup();
                        break;
                    }
                    case level_cardCompositionConst_1.level_cardCompositionCardType.query: {
                        // 卡牌翻开
                        card.cardToflip();
                        cards[composition].push(card);
                        minCard = Math.min(composition, minCard);
                        maxCard = Math.max(composition, maxCard);
                        break;
                    }
                    case level_cardCompositionConst_1.level_cardCompositionCardType.obstacles: {
                        obstaclesAry.push(card);
                        break;
                    }
                }
            }
            gs.spliceAllCards();
        });
        var oneCard = [];
        var canDealCardGroup = this.getCanDealCardGroup(0);
        for (var i = canDealCardGroup.length - 1; i >= 0; i--) {
            var group = canDealCardGroup[i];
            var composition = i + this.createMinCardNum;
            var ary = cards[composition] || [];
            for (var i_1 = 0; i_1 < ary.length; i_1++) {
                var card = ary[i_1];
                ary[i_1] = null;
                oneCard.push(card);
                if (group.getCurCardsLength() < group.getMaxCardsLength()) {
                    group.pushCard(card, false, true, false).then(function () {
                        _this.canTouch = true;
                    });
                }
                else {
                    ary[i_1] = null;
                    this.putOneCard(card.node);
                }
            }
            group.pushCardEnd(oneCard);
        }
        for (var i = 0; i < cards.length; i++) {
            for (var j = 0; j < ((_a = cards[i]) === null || _a === void 0 ? void 0 : _a.length); j++) {
                var c = cards[i][j];
                if (c) {
                    this.putOneCard(c.node);
                }
            }
        }
        for (var i = 0; i < obstaclesAry.length; i++) {
            var card = obstaclesAry[i];
            this.putOneCard(card.node);
        }
        for (var i = 0; i < universalAry.length; i++) {
            var card = universalAry[i];
            this.putOneCard(card.node);
        }
        // let canDealCardGroup2 = this.getCanDealCardGroup(1);
        // for(let i = 0;i<canDealCardGroup2.length;i++){
        //     let group = canDealCardGroup2[i];
        //     let twoCards:level_cardComposition_card[] = [];
        //     while(universalAry.length > 0 && group.getMaxCardsLength() - group.getCurCardsLength() > 0){
        //         let card = universalAry.pop();
        //         twoCards.push(card);
        //         group.pushCard(card,false,true);
        //     }
        //     group.pushCardEnd(twoCards);
        // }
    };
    /**打开介绍界面 */
    level_cardComposition.prototype.openIntroduction = function () {
        return __awaiter(this, void 0, void 0, function () {
            var type, page, p;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (this.introductionStack.length <= 0) {
                            return [2 /*return*/];
                        }
                        if (this.openIntroductionFlag) {
                            return [2 /*return*/];
                        }
                        type = this.introductionStack.shift();
                        if (this._introductionAry.includes(type)) {
                            this.openIntroduction();
                            return [2 /*return*/];
                        }
                        this._introductionAry.push(type);
                        this.writeData();
                        this.openIntroductionFlag = true;
                        return [4 /*yield*/, MainRoot_1.default.UISystem.OpenPage(Enum_1.PAGE.CARD_INTRODUCTION)];
                    case 1:
                        page = _a.sent();
                        p = page;
                        p.bindType(type, function () {
                            _this.openIntroductionFlag = false;
                            _this.openIntroduction();
                        });
                        return [2 /*return*/];
                }
            });
        });
    };
    __decorate([
        property({ type: cc.Node, tooltip: "卡牌组Content" })
    ], level_cardComposition.prototype, "groupContent", void 0);
    __decorate([
        property({ type: cc.Node, tooltip: "卡牌Content" })
    ], level_cardComposition.prototype, "cardContent", void 0);
    __decorate([
        property({ type: cc.Prefab, tooltip: "卡片预制体" })
    ], level_cardComposition.prototype, "cardP", void 0);
    __decorate([
        property({ type: cc.Prefab, tooltip: "组预制体" })
    ], level_cardComposition.prototype, "groupP", void 0);
    __decorate([
        property({ type: cc.Node, tooltip: "点击节点" })
    ], level_cardComposition.prototype, "touchNode", void 0);
    __decorate([
        property({ type: cc.Node, tooltip: "彩带节点" })
    ], level_cardComposition.prototype, "coloured", void 0);
    level_cardComposition = __decorate([
        ccclass
    ], level_cardComposition);
    return level_cardComposition;
}(LevelBase_1.default));
exports.default = level_cardComposition;

cc._RF.pop();